define(['../model/data','./intRender','./LocRender',
        '../business/pricecalc','./adword', '../plugins/account','di',
        '../plugins/hybrbox','../plugins/range'],function(DATA,iRender,lRender,pcalc,word,account,di,box,range){
    /***
    **index: 第几组
    **/
    return function(id,node,da,index){

        node = node||$("#"+id+" .user-body>li:first");
        switch(id){
            case "CustomAudience"://自定义受众
                setTimeout(function(){
                    node.find(".hybrbox").hybrbox({list:(DATA.aca),data:da})
                        .on("accountChange",function(e,o){
                            var nodeIndex = node.attr("index");
                            da.fbAccountName = o.data.fbAccountName;
                            da.fbAccountId = o.data.fbAccountId;
                            da.isClude = true;
                            da.isSupportCustomAudience = true;
                            da.dataIndex = o.index;
                            da.customAudiences = [];
                            DATA.update(id,nodeIndex,da);
                        }).on("cludeChange",function(e,o){
                            var nodeIndex = node.attr("index");
                            da.isClude = (o.data.value==0)?false:true;
                            if(da.customAudiences){
                                da.customAudiences.forEach(function(item){
                                    item.isClude = da.isClude;
                                });
                            }
							da.isSupportCustomAudience = false;
                            DATA.update(id,nodeIndex,da);
                        }).on("addTag",function(e,o){
                            var nodeIndex = node.attr("index");
                            if(!da.customAudiences) da.customAudiences = [];
                            da.customAudiences.push({id:o.id,name:o.name,isClude:da.isClude});
                            DATA.update(id,nodeIndex,da);
                        }).on("removeTag",function(e,o){
                            var nodeIndex = node.attr("index");
                            if(!da.customAudiences) da.customAudiences = [];
                            var idx = da.customAudiences.indexOf(o);
                            da.customAudiences.splice(idx,1);
                            DATA.update(id,nodeIndex,da);
                        });
                });
                break;
            case "price-config-field"://广告定价
                //排期组件
                $("#period-date").off('change').on('change',function(){
                    var sumbueget=$("#price-config-field").find("li:has(div.drop-budgetType:has(input[theValue='总预算']))");
                    sumbueget.each(function(i,o){
                        //da.type =1
                        var bprice= $(this).find('.b-price');
                        //重新校验预算
                        bprice.trigger("keyup");
                    })
                });

                //构造优化方向列表
                var optimizationGoalList;
                if (DATA.app.productType  == 'outlink'){
                    //外链
                    optimizationGoalList = DATA.bidInfo.outlink.optimizationGoalList;
                } else {
                    //应用
                    optimizationGoalList = DATA.bidInfo.app.optimizationGoalList;
                    var _cpa = _.findWhere(_.findWhere(optimizationGoalList, {id:"APP_INSTALLS"}).billingEvents, {id:"APP_INSTALLS"});

                    if ('Y' == DATA.sessionData.isSupportCpa){
                        //支持CPA
                        _cpa.text = I18N.getText('createAd', 'appInstalls');
                        _cpa.disable = 0;
                    } else {
                        //不支持CPA
                        _cpa.text = I18N.getText('createAd', 'appInstalls') + I18N.getText('createAd', 'appInstallsNoPermission');
                        _cpa.disable = 1;
                    }
                }
                //优化方向
                node.find("[name = 'drop-optGoal']").empty().bootDrop({
                    list:optimizationGoalList,
                    value:0,//base 1
                    prop:"text"
                }).off("selectChanged").on("selectChanged",function(e,o){
                    var gIndex=node.closest(".one-dist").attr("loc-index");
                    var locIndex= node.closest(".single-price").attr("index");
                    var info=DATA.getBidInfoVo(gIndex, locIndex);
                    info.optimizationGoal = o.data.id;

                    // 联动收费方式
                    node.find("[name='drop-billingEvent']").empty().bootDrop({
                        list: o.data.billingEvents,
                        value:0,//base 1
                        prop:"text"
                    });

                    node.find("[name='drop-billingEvent']").trigger("selectChanged", {index:0, data: o.data.billingEvents[0]});
                    if (info.optimizationGoal == "APP_INSTALLS" && info.billingEvent == "APP_INSTALLS") {
                        node.find('input[type=radio][value="'+I18N.getText('createAd', 'automatic')+'"]').attr("disabled","true");
                        node.find('input[type=radio][value="'+I18N.getText('createAd', 'manual')+'"]').trigger("click");
                    }else {
                        node.find('input[type=radio][value="'+I18N.getText('createAd', 'automatic')+'"]').removeAttr("disabled");
                    }
                    //更新出价提示
                    kit.pricerange2(node, DATA);
                });

                //收费方式
                var _initBillingEventConfig;
                if (DATA.app.productType  == 'outlink'){
                    //默认链接点击量对应的收费方式
                    _initBillingEventConfig = _.findWhere(optimizationGoalList, {id:"LINK_CLICKS"}).billingEvents;
                } else {
                    //默认安装对应的收费方式
                    _initBillingEventConfig = _.findWhere(optimizationGoalList, {id:"APP_INSTALLS"}).billingEvents;
                }

                node.find("[name='drop-billingEvent']").empty().bootDrop({
                    list: _initBillingEventConfig,
                    value:0,//base 1
                    prop:"text"
                }).off("selectChanged").on("selectChanged",
                    function(e,o){
                    var gIndex = node.closest(".one-dist").attr("loc-index");
                    var locIndex = node.closest(".single-price").attr("index");
                    var info = DATA.getBidInfoVo(gIndex, locIndex);
                    info.billingEvent = o.data.id;

                    if (info.optimizationGoal == "APP_INSTALLS" && info.billingEvent == "APP_INSTALLS") {
                        node.find('input[type=radio][value="'+I18N.getText('createAd', 'automatic')+'"]').attr("disabled","true");
                        node.find('input[type=radio][value="'+I18N.getText('createAd', 'manual')+'"]').trigger("click");
                    }else {
                        node.find('input[type=radio][value="'+I18N.getText('createAd', 'automatic')+'"]').removeAttr("disabled");
                    }

                    //切换收费方式 单价提示修改：投放控制上限
                    kit.pricerange2(node, DATA);
                    //切换收费方式 重新校验预算值
                    //重新校验单价
                    node.find("input[type].i-price").trigger("keyup");
                    //重新校验预算
                    node.find("input[type].b-price").trigger("keyup");
                    //修改支付方式重新渲染广告账号列表
                    account.initAccount(DATA.cache.entrustAccounts);
                });

                //预算类型
                node.find("[name='drop-budgetType']").empty().bootDrop({
                    list:[I18N.getText('createAd', 'dailyBudget'), I18N.getText('createAd', 'lifetimeBudget')],
                    value:0//base 1
                }).off("selectChanged").on("selectChanged",function(e,o){
                    var gIndex=node.closest(".one-dist").attr("loc-index");
                    var locIndex= node.closest(".single-price").attr("index");
                    var info=DATA.getBidInfoVo(gIndex, locIndex);
                    if (o.index == 1) {
                        if (DATA.SechduleType == 0) {
                            //当为排程为周期时，则切换到周期
                            $("#scheduletype").trigger("selectChanged",{index:1}).find("input").val(I18N.getText('createAd', 'cycle'));
                            $("#period-date").trigger("click");
                            kit.warning($("#period-date"));
                        }
                    }

                    info.budgetType = o.index;

                    //重新校验预算
                    node.find("input[type].b-price").trigger("keyup");
                });
                //是否是自动出价
                node.find("input[type='radio']").off("click").click(function(){
                    var gIndex=node.closest(".one-dist").attr("loc-index");
                    var locIndex= node.closest(".single-price").attr("index");
                    var info=DATA.getBidInfoVo(gIndex, locIndex);
                    var val=$(this).val();
                    if(val== I18N.getText('createAd', 'automatic')){
                        info.isAutoBid=1;
                        info.sBidAmount = 0;
                        var _iPriceGroup = $(this).closest("div").find(".i-price-group");
                        _iPriceGroup.css("visibility","hidden");
                        var _iPrice = $(this).closest("div").find(".i-price-group").find(".i-price");
                        _iPrice.addClass("hide");
                        _iPrice.val("").removeClass("anim_image_glow");
                        _iPrice.next("div.tooltip").css("opacity",0);
                        //重新校验预算
                        node.find("input[type].b-price").trigger("keyup");

                    }else {
                        info.isAutoBid=0;
                        $(this).closest("div").find(".i-price-group").css("visibility","visible");
                        $(this).closest("div").find(".i-price-group").find(".i-price").removeClass("hide");
                    }
                });

                //默认优化方向：应用安装 收费方式：展示次数 故支持自动出价
                node.find('input[type=radio][value="'+I18N.getText('createAd', 'automatic')+'"]').removeAttr("disabled");
                node.find('input[type=radio][value="'+I18N.getText('createAd', 'manual')+'"]').trigger("click");

                //单价
                node.find("input[type].i-price").numeral({'scale': 2});
                kit.pricerange2(node, DATA);
                node.find("input[type].i-price").off("keyup").keyup(function(e){
                    console.log("bid amount changed")
                    var gIndex=node.closest(".one-dist").attr("loc-index");
                    var locIndex= node.closest(".single-price").attr("index");
                    var info=DATA.getBidInfoVo(gIndex, locIndex);

                    var val = parseFloat($(this).val());
                    var max = $(this).attr("max");
                    var min = $(this).attr("min");
                    if(val<min){
                        $(this).addClass("error");
                        //小于FB接口下限，无法发布
                        $(this).next("div.tooltip").find(".tooltip-inner").addClass("warning-inner").text(I18N.getText('createAd','warn_priceMinLimit',min));
                        $(this).next("div.tooltip").css("opacity",1);
                    }else if (val>max) {
                        //大于投放控制上限 予以提示，但仍可以发布
                        $(this).removeClass("error");
                        $(this).next("div.tooltip").find(".tooltip-inner").removeClass("warning-inner").addClass("remind-inner").text(I18N.getText('createAd','tip_priceCaps',max));
                        $(this).next("div.tooltip").css("opacity",1);
                    }  else {
                        $(this).removeClass("error");
                        $(this).next("div.tooltip").css("opacity",0);
                        $(this).next("div.tooltip").find(".tooltip-inner").removeClass("warning-inner").removeClass("remind-inner");
                    }

                    //FB接口单价上限
                    if (val > 1000) {
                        $(this).addClass("error");
                        //大于FB接口下限，无法发布
                        $(this).next("div.tooltip").find(".tooltip-inner").addClass("warning-inner").text(I18N.getText('createAd','warn_priceMaxLimit',1000));
                        $(this).next("div.tooltip").css("opacity",1);
                    }

                    if ($(this).next("div.tooltip").find(".tooltip-inner").hasClass("warning-inner")) {
                        info.sBidAmount=0;
                        $(this).on("focusout",function(){
                            $(this).val("");
                            $(this).trigger("keyup", "");
                            $(this).off("focusout");
                        });
                    }else {
                        $(this).off("focusout");
                        info.sBidAmount= val || 0;
                    }

                    pcalc(info.budget,$(this).closest(".single-price").find("input.b-price"),info.budgetType);
                });
                //预算
                node.find("input[type].b-price").numeral({'scale': 2});
                node.find("input[type].b-price").off("keyup").keyup(function(e){
                    var gIndex=node.closest(".one-dist").attr("loc-index");
                    var locIndex= node.closest(".single-price").attr("index");
                    var info=DATA.getBidInfoVo(gIndex, locIndex);
                    var val = $(this).val();
                    info.budget=val;
                    pcalc(val,$(this),info.budgetType);

                });
                break;
            case "Age"://年龄
                var conditionAge = DATA.cache.adPublishConditionDetailCache.age;
                var ageM =  ageM ={
                    id : 'Age',
                    min: conditionAge.ageMin,
                    max: conditionAge.ageMax
                };
                if (DATA.nowTemp['Age'] && DATA.nowTemp['Age'][node.attr("index")]){
                    var cacheAge = DATA.nowTemp['Age'][node.attr("index")];
                    //如果有缓存则用缓存中的年龄
                    ageM.lefVal = cacheAge.ageMin < conditionAge.ageMin ?
                        conditionAge.ageMin : cacheAge.ageMin;
                    ageM.rigVal = cacheAge.ageMax > conditionAge.ageMax ?
                        conditionAge.ageMax : cacheAge.ageMax;
                } else {
                    //默认为投放控制中设置的年龄
                    ageM.lefVal = conditionAge.ageMin;
                    ageM.rigVal = conditionAge.ageMax;
                }
				DATA.update(id, node.attr("index"), {ageMin:ageM.lefVal, ageMax:ageM.rigVal});
                node.find("div.age-ranger").ranger(ageM).off("change").on("change",function(e,o){
                    var nodeIndex = node.attr("index");
                    //da.ageMin = o.min;
                    //da.ageMax = o.max;
                    DATA.update(id,nodeIndex,{ageMin:o.min,ageMax:o.max});
                });
                break;
            case "Interests"://兴趣
                var nodeIndex = node.attr("index");
                iRender(node,nodeIndex,da);
                break;
            case "Location"://地区
                var nodeIndex = node.attr("index");
                lRender(node,nodeIndex,da);
                break;
            case "WirelessConnection": //无线
                setTimeout(function(){
                    node.find("input[value="+(da[0])+"]").prop("checked",true);
                });
                $("ul.wifi-detail").find("input[type=radio]").unbind("click").click(function(e){
                    var l = $("ul.wifi-detail").children().length;
                    if(l==2){
                        e.stopPropagation();
                        e.preventDefault();
                        return kit.alert2(I18N.getText('createAd', 'notRepeat'));
                    }
                    //kit.addBorderGreen($(e.target).parents('.alert-dismissible').parent());
                });
                break;
            case "PageTypes"://版位
                /*    var val = parseInt((da&&Math.max.apply(null,da))||0);
                 if (val > 0 && da.length < 2 ){
                 //处理模板[1] 转为 [0,1]
                 DATA.update("PageTypes",node.attr("index"),1);
                 }
                 setTimeout(function(){
                 if(val) {
                 node.find("input[type=checkbox][value="+val+"]").prop("checked","checked");
                 }
                 },250);*/

                $('#PageTypes').off('click','input[type=checkbox]').on('click','input[type=checkbox]',function (e) {
                    var  $node = $(e.currentTarget).closest('li');
                    if(DATA.sessionData.isSupportInstagram=='Y'){
                        if(e.currentTarget.value==1){
                            if($node.find("input[type=checkbox][value=1]")[0].checked){
                                $node.find("input[type=checkbox][value=0]").prop("checked",false);
                                $node.find("input[type=checkbox][value=0]").trigger('click');
                            }
                        }else{
                            if(!$node.find("input[type=checkbox][value=0]")[0].checked){
                                $node.find("input[type=checkbox][value=1]").prop("checked",true);
                                $node.find("input[type=checkbox][value=1]").trigger('click');
                            }
                        }
                    }
                });
                break;
            case "Gender"://性别
                //根据广告发布条件渲染单选按钮
                var _genderHtml = '';
                $.each(DATA.Gender.GenderRenders, function(i, _genderRender){
                    _genderHtml += '<label><input type="radio" name="gender" value="' + _genderRender.val + '"' + (_genderRender.checked ? ' checked="checked"' : '') + '>' + _genderRender.name + '</label>'
                });
                node.find(".gender-radio").empty().html(_genderHtml);

                setTimeout(function(){
                    node.find("input[value="+(da[0])+"]").prop("checked",true);
                });
                var vals = [];
                $("#Gender").find("ul label:has(input[type=radio])").unbind("mousedown").on("mousedown",function(e){
                    vals = [];
                    $("#Gender").find("ul.user-body input[type=radio]:checked").each(function(idx,one){
                        vals.push($(one).val());
                    });
                });
                $("#Gender").find("label:has(input[type=radio])").unbind("click").on("click",function(e){
                    e.stopImmediatePropagation();
                    if(vals.length == DATA.Gender.GenderCount  ||vals.indexOf($(this).children("input").val())!=-1){
                        e.preventDefault();
                        return kit.alert(I18N.getText('createAd', 'notRepeatSettings'));
                    }
                });
                break;
            case "ad-txt"://广告词
                 node.find("textarea").val(DATA.adWords[index]).off("input").on('input', function(){
                    var len = $(this).val().length;
                    if(len==0){
                        $(this).next(".text-range-warning").text("");
                        //不能保存
                        //node.find(".save-slogan").("disabled");
                        node.find(".save-slogan").attr('disabled',true)
                    }else if(len < 90){
                        node.find(".save-slogan").removeAttr("disabled");
                        $(this).next(".text-range-warning").text(I18N.getText('createAd', 'canAlsoEnter',300-len));
                    }
                    else if(len>=90 && len<300){
                        node.find(".save-slogan").removeAttr("disabled");
                    	 $(this).next(".text-range-warning").text(I18N.getText('createAd','warnHidden', 90));
                    }
                    else if(len >=300){
                        node.find(".save-slogan").removeAttr("disabled");
                        $(this).next(".text-range-warning").text(I18N.getText('createAd','hasReached',300));
                    }
                     var nodeIndex = node.attr("index");
                     DATA.adWords[nodeIndex] = $(this).val();
                     DATA.cache.adWords = DATA.adWords;
                     DATA.sessionData.cache = JSON.stringify(DATA.cache);

                     if (kit.isAr($(this).val())) {
                         $(this).attr('dir', 'rtl');
                     } else {
                         $(this).removeAttr('dir', 'rtl');
                     }
                 });
                node.find("textarea").trigger("input");
                word();
                break;
        }
    }
});
